package com.example.service.impl;

import com.example.entity.dto.UserDTO;
import com.example.mapper.UserMapper;
import com.example.service.weChatService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Value;

import java.util.Random;
import java.util.UUID;

@Service
public class weChatServiceImpl implements weChatService {

    @Value("${wechat.app.id}")
    private String appId;

    @Value("${wechat.app.secret}")
    private String secret;

    @Resource
    private UserMapper userMapper;

    @Override
    public String login(String code){
        String url=String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",appId,secret,code);

        try{
            String result=new RestTemplate().getForObject(url,String.class);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public UserDTO autoRegister(String openId, String nickName, String avatar){
        UserDTO userDTO=new UserDTO();
        userMapper.weChatAutoRegister(openId,nickName,avatar);
        userDTO.setUID(openId);
        userDTO.setUsername(openId);
        userDTO.setName(nickName);
        userDTO.setRole("USER");
        userDTO.setAvatar(avatar);
        return userDTO;
    }
}
